import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/pages/home/record_history/model/device_details_resp.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import '../../../../common/model/base_resp.dart';
import '../../../../provider/global_provider.dart';
import '../../setting/model/get_setting_resp.dart';
import '../model/read_file_resp.dart';
import '../model/record_history_list_resp.dart';

mixin RecordHistoryMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  int pageNum = 1;
  bool showLoading = true;
  List<RecordHistoryData> historyList = <RecordHistoryData>[];
  late EasyRefreshController refreshController;
  bool isHigh = false; // 高清录音
  bool isAutoPlay = true; // 自动播放
  bool clickPlay = false;  //  点击后自动播放才生效
  bool deleteMode = false; // 删除模式
  bool isAllSelect = false; // 是否全选

  DeviceDetails? deviceDetails;

  int curPLayIndex = -1; // 当前播放的索引

  double sliderProgress = 0.3; // 灵敏度

  DateTime selectTime = DateTime.now(); // 选择的日期
  bool isRefreshTrackCalendar = false;  // 是否刷新过轨迹日历
  /// 日历日期值
  List<DateTime?> calendarValue = const [];
  /// 轨迹日历
  List<DateTime> trackCalendar = [];

  AudioPlayer audioPlayer = AudioPlayer();
  StreamSubscription? durationSubscription;
  StreamSubscription? playerCompleteSubscription;

  Future<ReadFileResp> readRecordFile(RecordHistoryData data) async {
    final res = await put<ReadFileResp, ReadFileResp>(
        '$newBaseULr/deviceFile/read/${data.fileId}',
        decodeType: ReadFileResp());
    return res.when(success: (resp) {
      return resp;
    }, failure: (String msg, int code) {
      XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
      return ReadFileResp();
    });
  }

  Future<ReadFileResp> deleteRecordFile(List<int?> fileIds) async {
    final res = await delete<ReadFileResp, ReadFileResp>(
        '$newBaseULr/deviceFile/remove/batch', data: fileIds,
        decodeType: ReadFileResp());
    return res.when(success: (resp) {
      return resp;
    }, failure: (String msg, int code) {
      XLogger.error('删除设备录音文件已读失败：msg: $msg, code: $code');
      return ReadFileResp();
    });

  }

  void getDeviceInfo() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<DeviceDetailsResp, DeviceDetailsResp>(
        '$newBaseULr/device/${deviceInfo.imei}',
        decodeType: DeviceDetailsResp());
    res.when(success: (resp) {
      setState(() {
        deviceDetails = resp.data;
        if (deviceDetails?.highVip == 0) {
          isHigh = false;
        }else {
          isHigh = deviceDetails?.highStatus == 0 ? false : true;
        }

        if (deviceDetails?.recordGears == 1) {
          sliderProgress = 1.0;
        }else if (deviceDetails?.recordGears == 2){
          sliderProgress = 0.66;
        }else if (deviceDetails?.recordGears == 4){
          sliderProgress = 0.33;
        }else {
          sliderProgress = 0.0;
        }
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备信息失败：msg: $msg, code: $code');
      deviceDetails = DeviceDetails();
    });
  }

  String formatDuration(int a) {
    int minutes = a ~/ 60;
    int seconds = a % 60;
    return "$minutes′$seconds″";
  }

  void selectAll() {
    isAllSelect = !isAllSelect;
    for (var element in historyList) {
      element.selected = isAllSelect;
    }
    setState(() {});
  }

  void deleteRecord() {
    List<int?> fileIds =
        historyList.where((e) => e.selected).map((e) => e.fileId).toList();
    deleteRecordFile(fileIds).then((value) {
      historyList.removeWhere((element) => fileIds.contains(element.fileId));
      setState(() {});
    });
  }

  void cancelDeleteMode() {
    setState(() {
      deleteMode = false;
      isAllSelect = false;
      for (var element in historyList) {
        element.selected = false;
      }
    });
  }

  void playRecord(RecordHistoryData data, int index) async {
    for (var element in historyList) {
      element.progress = 0;
    }
    if (curPLayIndex == index) {
      if (audioPlayer.state == PlayerState.playing) {
        debugPrint("停止");
        await audioPlayer.stop();
      } else {
        debugPrint("播放");
        await audioPlayer.play(UrlSource(data.path ?? ""));
      }
    } else {
      debugPrint("换一个");
      await audioPlayer.stop();
      await audioPlayer.play(UrlSource(data.path ?? ""));
      curPLayIndex = index;
    }
  }

  @override
  void dispose() {
    audioPlayer.stop();
    audioPlayer.release();
    super.dispose();
  }

  void setDevice({required dynamic data, VoidCallback? voidCallback}) async {
    XLogger.info(data);
    XLogger.info('${deviceDetails?.deviceName}');
    if (deviceDetails?.securityVip == 1) {
    } else {}

    ToastUtils.showLoading(status: "处理中...");
    final res =
        await post<ReadFileResp, ReadFileResp>('$newBaseULr/device/command',
            data: data,
            decodeType: ReadFileResp());
    res.when(success: (resp) async {
      getDeviceInfo();
      if(voidCallback != null){
        voidCallback();
      }
      ToastUtils.dismissLoading();
      ToastUtils.showSuccess("操作完成");
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
      XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
      return ReadFileResp();
    });
  }

  void changeStatus(String cmd, {required Function change}) async {
    ToastUtils.showLoading(status: "处理中...");
    XLogger.info('发送指令: $cmd');
     final deviceInfo = ref.read(deviceInfoProvider);
    final monitordata = ref.read(monitorDataProvider);
    XLogger.error(monitordata.deviceStatus);
     final postData = {
      'imei': deviceInfo.imei,
      'content': cmd,
      'cmdCode': cmd.split(',')[0],
    };
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('发送成功');
        change();
      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }
  /// 获取红点数据数组
  void getDayData( String imei, String year, String month, {required Function(List<DateTime> data) dataCallBack}) async {

    final res =
    await get<DateDataResp, DateDataResp>('$newBaseULr/deviceFile/dateFile?year=$year&month=$month&imei=$imei',
        decodeType: DateDataResp());
    res.when(success: (resp) async {
      XLogger.info(resp);
      List<DateTime> dataArr = [];
      if (resp.data != null) {
        for (DateMonthResp model in resp.data!) {
          if ((model.value ?? 0) > 0) {
            dataArr.add(DateTime.parse((model.date ?? "")));
          }
        }

        dataCallBack(dataArr);
}

    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
      XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
      return DateMonthResp();
    });
  }






}


